package com.xr.common.utils;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

@Slf4j
public class XrObjectConverter {

	public static Object mapToJavaBean(Map<?, ?> map, Class<?> clazz) {
		if (ObjectUtil.isEmpty(map)) {
			return null;
		}
		Object object = null;
		try {
			object = clazz.newInstance();
			// 获取自定义clazz类的全部字段
			Field[] fields = object.getClass().getDeclaredFields();
			for (Field field : fields) {
				// 获取字段修饰符 需要排除静态及final修饰的字段
				int modifiers = field.getModifiers();
				if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) {
					continue;
				}
				// 强制设置为 true 即可以对字段值进行设置 防止一些方法阻碍我们对属性进行赋值
				field.setAccessible(true);
				if (field.getType() == Integer.class) {
					field.set(object, Integer.valueOf(map.get(field.getName()).toString()));
				}
				else if (field.getType() == Long.class) {
					field.set(object, Long.valueOf(map.get(field.getName()).toString()));
				}
				else if (field.getType() == String.class) {
					field.set(object, map.get(field.getName()).toString());
				}
				else if (field.getType() == Boolean.class) {
					field.set(object, Boolean.valueOf(map.get(field.getName()).toString()));
				}
				else if (field.getType() == Date.class) {
					String dateString = map.get(field.getName()).toString();
					Date date = convertDateStringToDate(dateString);
					field.set(object, date);
				}
				else if (field.getType() == LocalDateTime.class) {
					String localDateTimeString = map.get(field.getName()).toString();
					LocalDateTime localDateTime = convertLocalDateTimeStringToDate(localDateTimeString);
					field.set(object, localDateTime);
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}

	private static Date convertDateStringToDate(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
		Date date = null;
		try {
			date = sdf.parse(dateString);
		}
		catch (Exception e) {
			log.error("解析错误，日期格式不合法！");
			e.printStackTrace();
		}
		return date;
	}

	private static LocalDateTime convertLocalDateTimeStringToDate(String localDateTimeString) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
		LocalDateTime localDateTime = null;
		try {
			localDateTime = LocalDateTime.parse(localDateTimeString, df);
		}
		catch (Exception e) {
			log.error("解析错误，日期格式不合法！");
			e.printStackTrace();
		}
		return localDateTime;
	}

}
